package com.intersult.nutils.net;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.log4j.Logger;

/**
 * @author Dieter Kaeppel
 * @date   16.11.2011
 */
public abstract class Server implements Runnable {
	private static final Logger log = Logger.getLogger(Server.class);
	
	private InetAddress bindAddress;
	private int port;
	private boolean stop;
	
	public Server(InetAddress bindAddress, int port) {
		this.bindAddress = bindAddress;
		this.port = port;
	}

	public int getPort() {
		return port;
	}

	/**
	 * Bind address, default bind if null.
	 */
	public InetAddress getBindAddress() {
		return bindAddress;
	}
	
	public void stop() {
		stop = true;
	}

	@Override
	public void run() {
		ServerSocket server;
		try {
			server = new ServerSocket(port, 0, bindAddress);
		} catch (IOException exception) {
			throw new IllegalArgumentException("Error creating server", exception);
		}
		while (!stop) {
			try {
				Socket incoming = server.accept();
				service(incoming);
			} catch (Exception exception) {
				log.error("Error serving request", exception);
			}
		}
		try {
			server.close();
		} catch (IOException exception) {
			throw new RuntimeException(exception);
		}
	}

	public abstract void service(Socket incoming) throws Exception;
}